package wec_wallet.ebo.com.activity.main;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;

import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent;
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEventListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import bassproject.ebo.com.ebobass.cropimage.ImagePicker;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import bassproject.ebo.com.ebobass.http_utils.utils.LoadingUtils;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.Lg;
import bassproject.ebo.com.ebobass.utils.StringUtil;
import bassproject.ebo.com.ebobass.view.CircleImageView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.activity.CodeActivity;
import wec_wallet.ebo.com.activity.MineActivity;
import wec_wallet.ebo.com.activity.SafeLevelActivity;
import wec_wallet.ebo.com.activity.options.ChangePhoneActivity;
import wec_wallet.ebo.com.activity.options.ServiceActivity;
import wec_wallet.ebo.com.utils.Functions;
import wec_wallet.ebo.com.utils.URLs;

/**
 * Created by admin on 2018/4/13.
 */

public class MineFragment extends AbsImageFragment {

    public static final int CODE_REQUEST = 998;
    public static final int CODE_REFRESH = 9999;
    @BindView(R.id.tv_mine_phone)
    TextView tvMinePhone;
    @BindView(R.id.layout_phone)
    RelativeLayout layoutPhone;
    @BindView(R.id.layout_service)
    RelativeLayout layoutService;
    @BindView(R.id.btn_verify_safe)
    RelativeLayout btnVerifySafe;
    @BindView(R.id.btn_change_language)
    RelativeLayout btnChangeLanguage;
    @BindView(R.id.layout_logout)
    RelativeLayout layoutLogout;
    @BindView(R.id.img_mine_photo)
    CircleImageView imgMinePhoto;
    @BindView(R.id.et_nickname)
    EditText etNickname;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.tv_language)
    TextView tvLanguage;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.iv_qrcode)
    ImageView ivQrcode;

    private String TAG = getClass().getSimpleName();
    private String mOldNickname = "";
    private String singlePath = "";
    private int mLevel = 0;

    public static MineFragment newInstance() {
        MineFragment f = new MineFragment();
        Bundle args = new Bundle();
        f.setArguments(args);
        return f;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View contentview = inflater.inflate(R.layout.fragment_mine, null);
        ButterKnife.bind(this, contentview);
        return contentview;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();

        if (etNickname.getText() != null)
            mOldNickname = etNickname.getText().toString();
        getUserInfo();
    }

    private void initViews() {
        //已绑定的手机
        String phone = I_Share.readAccountUsername_Phone();
        phone = StringUtil.toEncryption(phone);
        tvMinePhone.setText(phone);

        //已绑定的手机
        String nickname = I_Share.readNickname();
        etNickname.setText(nickname);
        if (TextUtils.isEmpty(etNickname.getText())) {
            tvNickname.setText(getString(R.string.nickname_undefine));
        } else {
            tvNickname.setText(etNickname.getText().toString());
        }

        etNickname.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {

                    return true;
                }
                return false;
            }
        });
        KeyboardVisibilityEvent.setEventListener(
                getActivity(),
                new KeyboardVisibilityEventListener() {

                    @Override
                    public void onVisibilityChanged(boolean b) {

                        // some code depending on keyboard visiblity status
                        if (!b) {
                            etNickname.setVisibility(View.GONE);
                            etNickname.clearFocus();
                            tvNickname.setVisibility(View.VISIBLE);
                            if (TextUtils.isEmpty(etNickname.getText())) {
                                tvNickname.setText(getString(R.string.nickname_undefine));
                            } else {
                                tvNickname.setText(etNickname.getText().toString());
                            }
                            modifyNickname(etNickname.getText().toString());
                        }
                    }
                });


        tvLanguage.setText(Functions.getLanguageName());

        String aPath = URLs.BASE_URL + "/" + I_Share.readAvatar();
        Lg.d(aPath);
        Picasso.get().load(aPath).into(imgMinePhoto);

    }

    @Override
    public void onFetchPhotoPostExcute(Bitmap bitmap, String orignalPath, String cropPath) {
        super.onFetchPhotoPostExcute(bitmap, orignalPath, cropPath);
        imgMinePhoto.setImageBitmap(bitmap);
        singlePath = cropPath;
        uploadAvatar(cropPath);
    }


    @OnClick(R.id.layout_phone)
    public void onLayoutPhoneClicked() {
        startActivity(new Intent(getActivity(), ChangePhoneActivity.class));
    }

    @OnClick(R.id.layout_service)
    public void onLayoutServiceClicked() {
        startActivity(new Intent(getActivity(), ServiceActivity.class));
    }

    @OnClick(R.id.btn_verify_safe)
    public void onBtnVerifySafeClicked() {
        Intent intent = new Intent(getActivity(), SafeLevelActivity.class);
        startActivityForResult(intent, CODE_REQUEST);
    }

    @OnClick(R.id.btn_change_language)
    public void onBtnChangeLanguageClicked() {
        IToast.show(getString(R.string.no_open));
//        startActivity(new Intent(getActivity(), LanguageSetActivity.class));
    }

    @OnClick(R.id.layout_logout)
    public void onLayoutLogoutClicked() {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getString(R.string.mine_logout))
                .setMessage(R.string.str_logoout)
                .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setNegativeButton(R.string.rc_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        show_Toast(getResources().getString(R.string.logout_success));
                        I_Share.cleanPassword();
                        Functions.relogin(getActivity());
                        getActivity().finish();
                    }
                });

        AlertDialog dialog = builder.create();
        dialog.show();
    }


    private void modifyNickname(String nickname) {
        if (I_Share.isLogin()) {
            Map<String, Object> postParams = new HashMap<>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            postParams.put("nickname", nickname == null || TextUtils.isEmpty(nickname) ? "" : nickname);
            Functions.post(getActivity(), URLs.CHANGE_NICKNAME, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {

                }

                @Override
                public void responseSuccess(String result) {

                    try {
                        if (Ipost.isSuccess(result)) {
                            I_Share.setNickname(etNickname.getText().toString());
                        } else {
                            IToast.show(Ipost.getErrorMsg(result));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, false, false);
        } else {
        }
    }


    private void getUserInfo() {
        if (I_Share.isLogin()) {
            Map<String, Object> postParams = new HashMap<>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            Functions.post(getActivity(), URLs.GET_USER_INFO, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {

                }

                @Override
                public void responseSuccess(String result) {

                    if (!TextUtils.isEmpty(result)) {
                        Type type = new TypeToken<MineActivity.UserInfo>() {
                        }.getType();
                        MineActivity.UserInfo resp = gson.fromJson(result, type);
                        if (resp != null && "0".equalsIgnoreCase(resp.getError())) {
                            mLevel = resp.getLevel();
                            tvLevel.setText(resp.getLevel() + "");
                        }
                    }

                }
            }, false, false);
        } else {
        }
    }


    @OnClick(R.id.img_mine_photo)
    public void onViewClicked2() {
        mImagePicker.pickImage(getActivity(), imgMinePhoto, ImagePicker.MODE_AVATAR);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (CODE_REFRESH == resultCode && requestCode == CODE_REQUEST) {
            Lg.d("getUserInfo");
            getUserInfo();
        }
    }


    protected void confirmAvatar(final String path, final String name) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("uid", I_Share.readAccountUserid());
        postParams.put("token", I_Share.readAccountToken());
        postParams.put("avatar", name);
        postParams.put("avatar_path", path);

        Functions.post(getActivity(), URLs.CHANGE_AVATAR, postParams, new IHttpPostListener() {
            @Override
            public void onTimeOut() {

            }

            @Override
            public void responseSuccess(String result) {
                Lg.d("头像上传成功");
                I_Share.setAvatar(path + name);
                LoadingUtils.progressDialogDismiss();
            }
        }, false, false);
    }

    @Override
    protected void handleMsg(Message msg) {
        super.handleMsg(msg);
        LoadingUtils.progressDialogShow(getActivity());
        String result = msg.obj.toString();
        String[] data = parseThumb(result);
        confirmAvatar(data[0], data[1]);
    }

    @OnClick(R.id.tv_nickname)
    public void onViewClicked() {
        etNickname.setVisibility(View.VISIBLE);
        tvNickname.setVisibility(View.GONE);
        etNickname.requestFocus();
        showKeyboard();
    }

    private void showKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(etNickname, 0);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick(R.id.iv_qrcode)
    public void onViewClicked22() {
        showLoading();
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("token", I_Share.readAccountToken());
        postParams.put("uid", I_Share.readAccountUserid());
        Functions.post(getActivity(), URLs.GET_QRCODE, postParams, new IHttpPostListener() {
            @Override
            public void onTimeOut() {
                dismissLoading();
            }

            @Override
            public void responseSuccess(String result) {

                try {


                    if (!TextUtils.isEmpty(result)) {
                        JSONObject jo = new JSONObject(result);
                        if("0".equalsIgnoreCase(jo.getString("error"))){
                            
                            JSONObject j1 = jo.getJSONObject("data");
                            String value = j1.getString("url");
                            startActivity(new Intent(getActivity(),CodeActivity.class).putExtra("code",value));
                        }

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }


                dismissLoading();

            }
        }, false, false);

    }
}
